<template>
    <el-container style="height: 820px; border: 1px solid #eee;padding: 5px">
        <el-main>
            <el-table
                    :data="buildingTable.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
                    style="width: 100%" height="720px">
                <el-table-column width="80px"
                                 label="宿舍楼"
                                 prop="name">
                </el-table-column>
                <el-table-column width="80px"
                                 label="区域"
                                 prop="block">
                </el-table-column>
                <el-table-column width="80px"
                                 label="单元数"
                                 prop="unit_count">
                </el-table-column>
                <el-table-column width="80px"
                                 label="层数"
                                 prop="floors">
                </el-table-column>
                <el-table-column
                        label="每单元每层房间数"
                        prop="rooms_per_floor">
                </el-table-column>
                <el-table-column
                        label="每间房床位数"
                        prop="beds_per_room">
                </el-table-column>
                <el-table-column
                        label="每间租金"
                        prop="general_room_rent"
                        sortable
                >
                </el-table-column>
                <el-table-column
                        label="备注"
                        prop="remark">
                </el-table-column>
                <el-table-column
                        label="创建日期"
                        prop="created_at">
                </el-table-column>
                <el-table-column
                        label="更新日期"
                        prop="updated_at">
                </el-table-column>
                <el-table-column
                        align="right" width="300px">
                    <template slot="header" slot-scope="scope">
                        <el-input
                                v-model="search"
                                size="mini"
                                placeholder="输入关键字搜索"/>
                    </template>
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="warning"
                                :disabled="scope.row.dorms_count>0"
                                @click="handleInit(scope.$index,scope.row)">初始化
                        </el-button>
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">更新
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">刪除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer>
            <el-form inLine="true">
                <el-button @click="createBuilding" type="primary">新增宿舍楼</el-button>
                <el-button @click="exportDorms" type="primary">导出宿舍初始化模板</el-button>
                <el-checkbox v-model="split2sheet">按楼分表导出</el-checkbox>
            </el-form>
        </el-footer>
        <el-dialog :title="(isEdit?'更新':'新增')+'宿舍信息'" width="40%"
                   :visible.sync="dialogFormVisible">
            <el-form :model="form" v-loading="loading" :rules="rules" ref="form">
                <el-form-item label="区域" :label-width="formLabelWidth" prop="block">
                    <el-input v-model="form.block"></el-input>
                </el-form-item>
                <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="单元数" :label-width="formLabelWidth" prop="unit_count">
                    <el-input-number v-model="form.unit_count" :min="1" :max="10"></el-input-number>
                </el-form-item>
                <el-form-item label="层数" :label-width="formLabelWidth" prop="floors">
                    <el-input-number v-model="form.floors" :min="1" :max="50"></el-input-number>
                </el-form-item>
                <el-form-item label="每层房间数" :label-width="formLabelWidth" prop="rooms_per_floor">
                    <el-input-number v-model="form.rooms_per_floor" :min="1" :max="40"></el-input-number>
                </el-form-item>
                <el-form-item label="每间床位数" :label-width="formLabelWidth" prop="beds">
                    <el-input-number v-model="form.beds_per_room" :min="1" :max="12"></el-input-number>
                </el-form-item>
                <el-form-item label="每间租用费" :label-width="formLabelWidth" prop="beds">
                    <el-input-number v-model="form.general_room_rent" :min="1" :max="1000"
                                     :precision="2"></el-input-number>
                </el-form-item>
                <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
                    <el-input v-model="form.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleForm">{{isEdit?'更新':'新增'}}</el-button>
            </div>
        </el-dialog>
        <el-dialog title="要导入的初始化数据" :visible.sync="dataDialogVisible">
            <el-table :data="dorms" height="500px">
                <el-table-column property="code" label="宿舍号" sortable></el-table-column>
                <el-table-column property="unit_name" label="单元" width="150"></el-table-column>
                <el-table-column property="floor" label="楼层" width="200"></el-table-column>
                <el-table-column property="rent" label="租金" width="200"></el-table-column>
                <el-table-column property="beds" label="床位数" width="200"></el-table-column>
                <el-table-column property="bed_rent" label="床位租金" width="200"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dataDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="importInit">确 定</el-button>
            </div>
        </el-dialog>
    </el-container>
</template>
<script>
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    export default{
        props: ['buildings'],
        data(){
            return {
                buildingTable: [],
                search: '',
                split2sheet: false,
                isEdit: false,
                formLabelWidth: '200px',
                dialogFormVisible:false,
                dataDialogVisible:false,
                dorms:[],
                loading: false,
                form: {
                    id: '',
                    block: '',
                    name: '',
                    unit_count: 1,
                    floors: 6,
                    rooms_per_floor: 6,
                    beds_per_room: 4,
                    general_room_rent: 200,
                    remark: ''
                },
                rules: {},
            }
        },
        created(){
            if (this.buildings) {
                this.buildingTable = this.buildings;
            } else {
                this.getBuildings();
            }
        },
        methods: {
            getBuildings(){
                axios.get('api/v1/building').then(result => {
                    this.buildingTable = result.data;
                });
            },
            createBuilding(){
                if (this.$refs['form']) {
                    this.$refs['form'].resetFields();
                }
                this.isEdit=false;
                this.dialogFormVisible = true;
            },
            handleEdit(index, row) {
                this.form = row;
                this.dialogFormVisible = true;
                this.isEdit = true;
            },
            handleDelete(index, row) {
                axios.get('api/v1/building/' + row.id+'/dormUsed').then(
                    result => {
                        if (result.data.dormUsed > 0) {
                            this.$confirm(row.name+'系统记录有人入住，如果删除那么入住人员将被设定为未安装住宿状态！' , '删除提示').then(() => {
                                axios.delete('api/v1/building/' + row.id).then(result => {
                                    this.$notify.success('删除成功');
                                    this.getBuildings();
                                }).catch(
                                    error => {
                                        this.$notify.error('删除失败');
                                        if( error.response ){
                                            console.log(error.response.data); // => the response payload
                                        }
                                    });
                            }).catch(action => {
                                //if(action=='cancel')console.log('cancel');
                            });
                        } else {
                            this.$confirm('确定删除' + row.name, '删除提示').then(() => {
                                axios.delete('api/v1/building/' + row.id).then(result => {
                                    this.$notify.success('删除成功');
                                    this.getBuildings();
                                }).catch(
                                    error => {
                                        this.$notify.error('删除失败');
                                        if( error.response ){
                                            console.log(error.response.data); // => the response payload
                                        }
                                    });
                            }).catch(action => {
                                //if(action=='cancel')console.log('cancel');
                            });
                        }
                    });
            },
            handleInit(index, row){
                axios.get('api/v1/building/' + row.id).then(
                    result => {
                        if (result.data.dorms_count > 0) {
                            this.$alert('已经投入使用不能初始化', '初始化提示');
                        } else {
                            var bed_rent=row.general_room_rent/row.beds_per_room;
                            if (/^\d+/.test(row.name.trim())) {
                                var b_name = row.name.trim().match(/^\d+/)[0];
                                for (var u = 1; u <= row.unit_count; u++) {
                                    for (var f = 1; f <= row.floors; f++) {
                                        for (var r = 1; r <= row.rooms_per_floor; r++) {
                                            var dorm_code=b_name+'#'+u+'D'+f+(r+'').padStart(2,'0');
                                            this.dorms.push({
                                                building_id:row.id,
                                                unit_name:u+'',
                                                code:dorm_code,
                                                floor:f,
                                                beds:row.beds_per_room,
                                                rent:row.general_room_rent,
                                                bed_rent:bed_rent
                                            });
                                        }
                                    }
                                }

                            } else {
                                var b_name = row.name.trim().replace('栋','').trim();
                                for (var u = 1; u <= row.unit_count; u++) {
                                    for (var f = 1; f <= row.floors; f++) {
                                        for (var r = 1; r <= row.rooms_per_floor; r++) {
                                            var dorm_code=b_name+u+f+(r+'').padStart(2,'0');
                                            this.dorms.push({
                                                building_id:row.id,
                                                unit_name:u+'',
                                                code:dorm_code,
                                                floor:f,
                                                beds:row.beds_per_room,
                                                rent:row.general_room_rent,
                                                bed_rent:bed_rent
                                            });
                                        }
                                    }
                                }
                            }
                            axios.post('api/v1/dorm/batchStore',this.dorms).then(result=>{
                                console.log(result);
                            }).catch(error=>{
                                if( error.response ){
                                    console.log(error.response.data); // => the response payload
                                }
                            });
                        }
                    });
            },
            handleForm(){
                if (this.isEdit) {
                    axios.put('api/v1/building/' + this.form.id, this.form).then(result => {
                        this.dialogFormVisible = false;
                        this.$notify.success('更新成功');
                        this.getBuildings();
                    }).catch(error => {
                        this.$notify.error('更新失败');
                        console.log(error);
                    });
                } else {
                    axios.post('api/v1/building', this.form).then(result => {
                        this.dialogFormVisible = false;
                        this.$notify.success('新增成功');
                        this.getBuildings();
                    }).catch(error => {
                        this.$notify.error('新增失败');
                        console.log(error);
                    });
                }
            },
            exportDorms(){
                axios.get('api/v1/dorm').then(result => {
                    var wb = XLSX.utils.book_new();
                    var dormCodes = result.data;
                    var dorms = [];
                    var b_name='';
                    var i=0;
                    if (dormCodes && dormCodes.length > 0) {
                        if(this.split2sheet){
                            dormCodes.forEach(c => {
                                if(i==0){
                                    dorms.push({ID:c.id,宿舍楼:c.buildingName,宿舍号: c.dormCode, 水表读数: 0, 电表读数: 0,抄表日期:new Date()});
                                    b_name=c.buildingName;
                                }else{
                                    if(c.buildingName!=b_name){
                                        var ws = XLSX.utils.json_to_sheet(dorms);
                                        wb.SheetNames.push(b_name);
                                        wb.Sheets[b_name]=ws;

                                        dorms=[];
                                        dorms.push({ID:c.id,宿舍楼:c.buildingName,宿舍号: c.dormCode, 水表读数: 0, 电表读数: 0,抄表日期:new Date()});
                                        b_name=c.buildingName;
                                    }else{
                                        dorms.push({ID:c.id,宿舍楼:c.buildingName,宿舍号: c.dormCode, 水表读数: 0, 电表读数: 0,抄表日期:new Date()});
                                    }
                                }
                                i++;
                                if(i==dormCodes.length){
                                    var ws = XLSX.utils.json_to_sheet(dorms);
                                    wb.SheetNames.push(b_name);
                                    wb.Sheets[b_name]=ws;
                                }
                            });

                        }else{
                            dormCodes.forEach(c => {
                                dorms.push({宿舍楼:c.buildingName,宿舍号: c.dormCode, 水表读数: 0, 电表读数: 0,抄表日期:new Date()});
                            });
                            var ws = XLSX.utils.json_to_sheet(dorms);
                            wb.SheetNames.push('all_dorms');
                            wb.Sheets.all_dorms = ws;
                        }
                    }

                    /* get binary string as output */
                    let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
                    try {
                        var fileName='所有宿舍水电表初始化模板'+(this.split2sheet?'-分楼':'')+'.xlsx';
                        FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), fileName);
                    } catch (e) {
                        if (typeof console !== 'undefined')
                            console.log(e, wbout)
                    }
                });
            },
        }
    }
</script>
